/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lottery.game.core.modules.service.app;

import com.lottery.game.common.exception.BaseException;
import com.lottery.game.common.utils.MD5Util;
import com.lottery.game.common.utils.MakeNoUtil;
import com.lottery.game.common.utils.UUIDUtils;
import com.lottery.game.common.utils.ValidateUtils;
import com.lottery.game.core.modules.entity.game.GameRoom;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.entity.user.UserRankPojo;
import com.lottery.game.core.modules.mapper.GameUserDao;
import com.lottery.game.core.modules.mapper.OperationalSetDao;
import com.lottery.game.core.modules.mapper.UserLoginDao;
import com.lottery.game.core.modules.mapper.UserRankDao;
import com.lottery.game.core.modules.service.redis.RedisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 游戏用户Service
 * @author chenye
 * @version 2018-03-25
 */
@Service
@Transactional(readOnly = true)
public class UserLoginService {

	@Autowired
	private UserLoginDao userLoginDao;

	@Autowired
	private UserRankDao userRankDao;

	@Autowired
	private GameUserDao gameUserDao;

	@Autowired
	private OperationalSetDao operationalSetDao;

	@Autowired
	private RedisService redisService;

	@SuppressWarnings("unchecked")
	public Map<String,String> validate_register(
			String username,
			String password,
			String phone,
			String phoneCode,
			String qq,
			String introducer,
			String address,
			HttpSession session)  throws Exception {
		Map<String,String> map = new HashMap<String, String>();

		if("".equals(username)||username==null) {
			map.put("message", "用户名不能为空");
			map.put("status", "fail");
			return map;
		}
		// 判断用户名是否正确  //4-18字母的组合，最少一个字母
		if(!ValidateUtils.isUserName(username)) {
			map.put("message", "用户名应为4到18 汉字、字母、数字的组合！");
			map.put("status", "fail");
			return map;
		}
		if(password.length()<6||password.length()>18) {
			map.put("message", "密码长度应为6到18位");
			map.put("status", "fail");
			return map;
		}
		if(!ValidateUtils.isNull(phone)) {
			map.put("message", "手机号不能为空！");
			map.put("status", "fail");
			return map;
		}
		if(!ValidateUtils.isNull(phoneCode)) {
			map.put("message", "验证码不能为空！");
			map.put("status", "fail");
			return map;
		}
		if(!ValidateUtils.isCode(phoneCode)) {
			map.put("message", "验证码格式错误！");
			map.put("status", "fail");
			return map;
		}
		// 判断手机验号是否正确
		if(!ValidateUtils.isMobile(phone)) {
			map.put("message", "手机号格式错误！");
			map.put("status", "fail");
			return map;
		}
		Object phone_code = session.getAttribute("regist_phone_code");
		if (phone_code == null || !(phone_code.toString().equals(phoneCode))) {
			// 验证码错误
			map.put("message", "手机验证码错误！");
			map.put("status", "fail");
			return map;
		}
		// 查询用户是否存在
		Integer b = this.userLoginDao.queryUserCount(username, phone);
		if (b != null && b.longValue() > 0) {
			// 用户名、手机、电子邮件存在
			map.put("message", "用户名或者手机已经存在！");
			map.put("status", "fail");
			return map;
		}
		//盐。 随机生成
		String salt = UUIDUtils.randomUUID();
		//生成订单号
		String no = MakeNoUtil.makeOrderNum();
		//密码加盐
		String pwd = MD5Util.MD532(MD5Util.MD532(password), salt);
		Date date = new Date();
		GameUser user = new GameUser(UUIDUtils.randomUUID(),username, pwd, phone, no,salt,qq,introducer,address,date);
		this.userLoginDao.insertUser(user);
		map.put("message", "注册成功!");
		map.put("status", "success");
		return map;
	}
	public Map<String,String> getGameUserBynamepwd2(String username,String password,String roomNo, HttpSession session) {
		String salt= this.userLoginDao.getSaltByUsername(username);
		Map<String, String> map = new HashMap<>(2);
		if(StringUtils.isEmpty(username)) {
			map.put("message", "用户名不能为空！");
			map.put("status", "fail");
		}else if(StringUtils.isEmpty(password)) {
			map.put("message", "密码不能为空！");
			map.put("status", "fail");
		}else if(StringUtils.isEmpty(salt)) {
			map.put("message", "用户名或者密码错误！");
			map.put("status", "fail");
		}else {
			String pwd = MD5Util.MD532(MD5Util.MD532(password), salt);
			GameUser gameUser= this.userLoginDao.getGameUserBynamepwd(username,pwd);
			if(gameUser!=null) {
				gameUser.setRoomNo(roomNo);
				session.setAttribute("GAMEUSER", gameUser);
				map.put("message", "登录成功！");
				map.put("status", "success");
				// 查询房间是否存在
				//TODO:判断房间意义？？？？
				if(!StringUtils.isEmpty(roomNo)){
					try {
						GameRoom gameRoom = this.userLoginDao.queryRoomCount(roomNo);
						if (gameRoom == null) {
							map.put("message", "该房间不存在！");
							map.put("status", "fail");
						}else {
							System.out.println("有房间");
							//roomMap.put("room", gameRoom);
						}
					}catch (Exception e){
						e.printStackTrace();
					}

				}
			}else{
				map.put("message", "用户名或者密码错误！");
				map.put("status", "fail");
			}
		}
		return map;
	}

	public Map<String,Object> getGameUserBynamepwd(String username,String password, HttpSession session,Map<String,Object> roomMap,String loginEnvironment, HttpServletRequest request) {
		Map<String,Object> map=new HashMap<String, Object>(32);
		// 判断号是否正确
		if(StringUtils.isEmpty(username)) {
			throw new BaseException("用户名不能为空！");
		}else{
			//TODO:可优化
			// salt 参考GameUserService.validate_register  salt是通过UUID随机生成的
			String salt = this.userLoginDao.getSaltByUsername(username);
			if(StringUtils.isEmpty(password)) {
				throw new BaseException("密码不能为空！");
			}else if("".equals(salt)||null==salt) {
				throw new BaseException("找不到该用户, 查询的用户名：" + username);
			}else{
				String pwd = MD5Util.MD532(MD5Util.MD532(password), salt);

				GameUser gameUser= this.userLoginDao.getGameUserBynamepwd(username,pwd);
				if (gameUser != null) {
					//查询user的封号状态
					String banAccount  = gameUser.getFenghaostatus();
					if(!StringUtils.isEmpty(banAccount) && "1".equals(banAccount)) {
						throw new BaseException("该用户名已经封停，用户名是：" + username);
					}
					String ip= request.getRemoteAddr();
					Map<String, Object> ipBlacklistMap = this.operationalSetDao.queryIPBlacklist(ip);
					if(ipBlacklistMap != null) {
						throw new BaseException("黑名单用户，用户名是：" + username);
					}
					session.setAttribute(gameUser.getPhone(), gameUser.getPhone());
					map.put("message", "登录成功！");
					map.put("status", "success");
					map.put("username",gameUser.getUsername());
					map.put("salt",gameUser.getSalt());
					map.put("nickname",gameUser.getNickname());// 昵称
					map.put("phone",gameUser.getPhone());// 电话
					map.put("no",gameUser.getNo());// 用户帐号
					map.put("balance",gameUser.getBalance());// 余额
					map.put("point",gameUser.getPoint());// 积分
					map.put("wechat",gameUser.getWechat());// 微信
					map.put("qq",gameUser.getQq());// qq
					map.put("introducer",gameUser.getIntroducer());//介绍人
					map.put("alipay",gameUser.getAlipay());// 支付宝账号
					map.put("account",gameUser.getAccount());// 下分账户
					map.put("ip",gameUser.getIp());// ip
					map.put("agent",gameUser.getAgent());// 代理
					map.put("superiors",gameUser.getSuperiors());// 上级
					map.put("createAdress",gameUser.getCreateAdress());// 创建地区
					map.put("roomNo",gameUser.getRoomNo());	// 状态
					map.put("chatstatus",gameUser.getStatus());	// 状态
					map.put("fenghaostatus",gameUser.getFenghaostatus());//账号或者IP状态
					//IP检测功能暂停 临时处理
					if(StringUtils.isEmpty(gameUser.getLogin_ip_area())){
						map.put("loginIpArea","0.0.0.0|未开启");
					}else{
						map.put("loginIpArea", gameUser.getLogin_ip_area());
					}

					map.put("photourl",gameUser.getPhotourl());	// 头像路径
					if(StringUtils.isEmpty(gameUser.getPayment_assword())) { //判断用户是否有支付密码
						map.put("paymentPassword","false");
					}else {
						map.put("paymentPassword","true");
					}
					UserRankPojo userRank = new UserRankPojo();
					userRank.setQueryAmount(gameUser.getBalance());
					userRank = this.userRankDao.getUserRank(userRank );
					map.put("userRank",userRank);  // 用户级别
					String terminalType = (String) session.getAttribute("terminalType");
					String uuid=UUIDUtils.randomUUID();
					//String accessToken = TokenUtils.create(uuid, terminalType, gameUser.getId());
					String accessToken = "";
					map.put("uuid",uuid);
					map.put("terminalType",terminalType);
					map.put("token",accessToken);//返回token
					map.put("userId",gameUser.getId());

					this.redisService.set("TOKEN"+gameUser.getId(), accessToken);
					this.redisService.set("UUID"+gameUser.getId(), uuid);
					String newDate = String.valueOf(System.currentTimeMillis());
					this.redisService.set("USERID"+gameUser.getId(),newDate); //设置当天时间
				}else {

					throw new BaseException("用户名或者密码错误！");
				}
			}
		}
		return map;
	}

	public Map<String,Object> getGameUserListdata(Map<String,Object> map) {
		return this.userLoginDao.getGameUserListdata(map);
	}

	public Map<String,Object> getGameUserLevel(Map<String,Object> map) {
		return this.userLoginDao.getGameUserLevel(map);
	}
	public Integer getGameUserListdataCount(Map<String,Object> map) {
		return this.userLoginDao.getGameUserListdataCount(map);
	}

	public Integer queryAccessTokenByToken(String accessToken){
		return this.userLoginDao.queryAccessTokenByToken(accessToken);
	}

	public Integer queryAccessTokenByClientId(String clientId){
		return this.userLoginDao.queryAccessTokenByClientId(clientId);
	}

	public GameUser getUserByPhone(String phone){
		return this.userLoginDao.getUserByPhone(phone);
	}


}
